package com.jilintongyi.jlcrtvu.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jilintongyi.jlcrtvu.entity.SysLog;
import com.jilintongyi.jlcrtvu.service.LogService;
import com.jilintongyi.jlcrtvu.util.HttpUtils;

/**
 * 登录失败处理
 */
@Component
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	@Autowired
	LogService logService;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		SysLog log = new SysLog();
		ObjectMapper objectMapper = new ObjectMapper();
		log.setContent("登录失败 " +
				objectMapper.writeValueAsString(request.getParameterMap()));
		log.setIp(HttpUtils.getIpAddress(request));
		logService.save(log);
		// 登录失败带回值
		HttpSession session = request.getSession();
		session.setAttribute("username", request.getParameter("username"));// 带回用户名
		session.setAttribute("rememberMe", request.getParameter("remember-me"));// 带回自动登录选择
		// 失败跳转
		setDefaultFailureUrl("/login?error");
		super.onAuthenticationFailure(request, response, exception);
	}
}
